<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-button size="medium" type="primary" class="filter-item" style="font-weight: bold;">使用中人数总数:{{currentNumbersTotal}}</el-button>
        </el-form-item>

        <el-form-item label="">
          <el-input v-model="formInline.payMemberName" :placeholder="$t('请输入付费会员名称')" clearable></el-input>
        </el-form-item>

        <!-- <el-form-item>
          <el-date-picker style="vertical-align: top; width:300px;" v-model="totalAddTime" type="daterange" @change="changeDate"  value-format="yyyy-MM-dd"
            range-separator="——" :start-placeholder="$t('添加开始日期')" :end-placeholder="$t('添加结束日期')">
          </el-date-picker>
        </el-form-item> -->

        <el-form-item>
          <el-date-picker style="vertical-align: top; width:300px;" v-model="totalStartTime" type="daterange" @change="changeStartDate"  value-format="yyyy-MM-dd"
            range-separator="——" :start-placeholder="$t('开始时间开始日期')" :end-placeholder="$t('开始时间结束日期')">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-date-picker style="vertical-align: top; width:300px;" v-model="totalEndTime" type="daterange" @change="changeEndDate"  value-format="yyyy-MM-dd"
            range-separator="——" :start-placeholder="$t('结束时间开始日期')" :end-placeholder="$t('结束时间结束日期')">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="info" icon="el-icon-search" v-permission="['GET /admin/p/member_pay_index']" @click="handleFilter">{{$t('Search')}}</el-button>
          <el-button type="warning" plain1 icon="el-icon-circle-plus" v-permission="['GET /admin/p/member_pay_add']" @click="handleCreate">{{$t('Add')}}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" :element-loading-text="$t('Searching')" border fit
              highlight-current-row>
      <el-table-column align="center" type="index" :label='$t("序号")' :index="getIndex" width="50"></el-table-column>
      <el-table-column align="center" :label='$t("付费会员名称")' prop="name"/>
      <el-table-column align="center" :label='$t("人数")' prop="numbers"/>
      <el-table-column align="center" :label='$t("使用中人数")' prop="currentNumbers"/>
      <el-table-column align="center" :label='$t("占比")' prop="per"/>
      <el-table-column align="center" :label='$t("图片")' prop="picUrl">
        <template slot-scope="scope">
          <el-image preview-src-list style="border-radius:15%;width:60px" :src="scope.row.picUrl" lazy>
            <div slot="error" class="image-slot">
              <i style="font-size: 30px" class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" :label='$t("允许自动续订")' prop="isSupportReneval">
        <template slot-scope="scope">
          <span>{{scope.row.isSupportReneval==true?'是':'否'}}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" :label='$t("金额")' prop="money">
        <template slot-scope="scope">
          <span style="display: block;">{{handleMoney(scope.row)}}</span>
          <span style="display: block;">{{$t('或者')}}</span>
          <span style="display: block;">{{handlePoint(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="left" :label='$t("续费金额")' prop="renevalMoney">
        <template slot-scope="scope">
          <span style="display: block;">${{scope.row.renevalMoney}}</span>
          <span style="display: block;">or</span>
          <span style="display: block;">{{scope.row.renevalPoint}}{{$t('积分')}} </span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label='$t("使用范围")' prop="addUserName">
        <template slot-scope="scope">
          <span>{{$t(scope.row.useRange==1?'门店使用':scope.row.useRange==2?'网店使用':'通用')}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label='$t("区域限制")' prop="areaLimit">
        <template slot-scope="scope">
          <el-tag>{{filterAreaLimit(scope.row)}}</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" :label='$t("添加时间")' prop="addTime">
        <template slot-scope="scope">
          <span style="display: block;">{{formatDate(scope.row.addTime)}}</span>
          <span style="display: block;">{{formatTime(scope.row.addTime)}}</span>
        </template>
      </el-table-column> -->
      <el-table-column align="center" :label='$t("开始时间")' prop="startTime">
        <template slot-scope="scope">
          <span style="display: block;" >{{formatDateTime(scope.row.startTime)}}</span>
          <span style="display: block;" >{{formatTime(scope.row.startTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label='$t("结束时间")' prop="endTime">
        <template slot-scope="scope">
          <span style="display: block;" >{{formatDateTime(scope.row.endTime)}}</span>
          <span style="display: block;" >{{formatTime(scope.row.endTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label='$t("状态")' prop="type">
        <template slot-scope="scope">
          <el-tag>{{$t(scope.row.status==1?'新增':scope.row.status==2?'启用':scope.row.status==3?'停用':scope.row.status)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('Operate')" width="250" class-name="small-padding fixed-width">
        <template slot="header" slot-scope="{row}">
          {{$t('Operate')}}
          <i class="el-icon-setting"style="color: #d35e32"></i>
        </template>
        <template slot-scope="scope">
          <el-link icon="el-icon-view"  type="primary" plain1 size="mini"  @click="handleDetail(scope.row)" v-permission="['GET /admin/p/member_pay_detail']">
            {{$t(scope.row.status!=2 ? '编辑':'查看')}}
          </el-link>
          <el-link type="danger" icon="el-icon-delete" plain1 size="mini" v-if="scope.row.status!=2" @click="handleDelete(scope.row)" v-permission="['GET /admin/p/member_pay_delete']">
            {{$t('Delete')}}
          </el-link>
          <el-link icon="el-icon-turn-off" type="warning" plain1 size="mini" v-if="scope.row.status!=2" @click="updateStatus(scope.row)" v-permission="['GET /admin/p/member_pay_status']"> {{$t('Enable')}}
          </el-link>
          <el-link icon="el-icon-open" type="warning" plain1 size="mini" v-if="scope.row.status==2" @click="updateStatus(scope.row)" v-permission="['GET /admin/p/member_pay_status']"> {{$t('Disable')}}
          </el-link>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"/>

    <el-tooltip placement="top" :content="$t('Back_to_top')">
      <back-to-top :visibility-height="100"/>
    </el-tooltip>
  </div>
</template>
<script>
  import ElSelectDropdown from 'element-ui/packages/select/src/select-dropdown'
  import BackToTop from '@/components/BackToTop'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  import { listGiftCard, deleteGiftCard, updateStatus } from '@/api/gift'
  import { formatDate } from '@/utils/date'

  import {
    payMemberList,
    payMemberDeletes, payMemberUpdateStatus
  } from '@/api/user'

  export default {
    name: 'PaidMemberSettings',
    components: { ElSelectDropdown, BackToTop, Pagination },
    data() {
      // // 获取当前日期前一周的日期作为添加时间的起始日期
      // const addTimeStartDate = formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd')
      // // 获取当前日期作为添加时间的结束日期
      // const addTimeEndDate = formatDate(new Date(), 'yyyy-MM-dd')

      // 获取当前日期前一周的日期作为开始时间的起始日期
      const startTimeStartDate = formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd')
      // 获取当前日期作为开始时间的结束日期
      const startTimeEndDate = formatDate(new Date(), 'yyyy-MM-dd')

      // 获取当前日期前一周的日期作为结束时间的起始日期
      const endTimeStartDate = formatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd')
      // 获取当前日期作为结束时间的结束日期
      const endTimeEndDate = formatDate(new Date(), 'yyyy-MM-dd')

      const typeMap = ['', '全场通用']
      return {
        value1: '',
        // totalAddTime: [],
        totalStartTime:[],
        totalEndTime: [],
        //参数
        formInline: {
          payMemberName: undefined,       // 支付成员名
          // addTimeStartDate: undefined,    // 添加时间起始日期
          // addTimeEndDate: undefined,      // 添加时间结束日期
          startTimeStartDate: undefined,     // 开始日期起始日期
          startTimeEndDate: undefined,       // 开始日期结束日期
          endTimeStartDate: undefined,       // 结束日期起始日期
          endTimeEndDate: undefined,         // 结束日期结束日期
          page: 1,                        // 页码，默认为 1
          limit: 50,                      // 每页限制，默认为 50
          sort: 'add_time',               // 排序字段，默认为添加时间
          order: 'desc'                   // 排序顺序，默认为降序
        },
        typeMap,
        list: [],
        total: 0,
        currentNumbersTotal: undefined,
        listLoading: false,
        listQuery: {
          page: 1,
          limit: 20,
          name: undefined,
          sort: 'add_time',
          order: 'desc'
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      // /**
      //  * 处理日期变化事件，当日期值为null时，重置总添加时间列表为一个空数组，并调用getList方法重新获取数据
      //  * @param {Date} value - 日期值
      //  */
      // changeDate(value) {
      //   if (value === null) {
      //     this.totalAddTime = [];
      //   }
      //   this.getList();
      // },

      changeStartDate(value) {
        if (value === null) {
          this.totalStartTime = [];
        }
        this.getList();
      },

      changeEndDate(value) {
        if (value === null) {
          this.totalEndTime = [];
        }
        this.getList();
      },

      getList() {
        this.listLoading = true
        // this.formInline.addTimeStartDate = this.totalAddTime[0];
        // this.formInline.addTimeEndDate = this.totalAddTime[1];

        this.formInline.startTimeStartDate = this.totalStartTime[0];
        this.formInline.startTimeEndDate = this.totalStartTime[1];

        this.formInline.endTimeStartDate = this.totalEndTime[0];
        this.formInline.endTimeEndDate = this.totalEndTime[1];

        payMemberList(this.formInline).then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
          this.columnSum()
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      },
      handleDelete(row) {
        this.$confirm(this.$t('Confirm_Delete?'), this.$t('Hint'), {
          confirmButtonText: this.$t('Confirm'),
          cancelButtonText: this.$t('Cancel'),
          type: 'warning'
        }).then(() => {
          this.doDelete(row)
        })
      },
      doDelete(row) {
        var memberId = row.id
        payMemberDeletes(memberId).then(response => {
          this.$notify.success({
            title: this.$t('Success!'),
            message: this.$t('Deleted')
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        }).catch(response => {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t(response.data.errmsg)
          })
        })
      },
      updateStatus(row) {
        // scope.row.status==1?'新增':scope.row.status==2?"启用":scope.row.status==3?'停用':scope.row.status
        var mag = row.status == 1 ? '启用' : row.status == 2 ? '停用' : row.status == 3 ? '启用' : row.status
        // var mag= row.status==0?'上架':row.status==1?"下架":row.status==2?'上架':row.status
        if(row.currentNumbers != 0){
          this.$message.error('使用人员为空，才能停用');
        }else{
          this.$confirm('确定' + mag + '吗?, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            payMemberUpdateStatus(row.id).then(res => {
              this.$message({
                type: 'success',
                message: mag + '成功!'
              })
              this.getList()
            }).catch(res => {
              this.$message({
                type: 'warning',
                message: res.data.errmsg
              })
              // this.getList()
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消成功'
            })
          })
        }
      },
      handleFilter() {
        let dt = new Date(this.formInline.addTime)
        if (isNaN(dt)) {
          this.formInline.addTime = undefined
        } else {
          let getDate = dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate()
          let dataTime = dt.getFullYear() + '-' + (dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1) + '-' + getDate
          this.formInline.addTime = dataTime
        }

        this.getList()
      },
      handleCreate() {//新增
        this.$router.push({ path: '/user/PaidMemberSettings/addedPaidUser', query: { type: 1 } })
      },
      handleEdit(row) {//卡号统计
        this.$router.push({ path: '/promotion/cardStatistics' })
      },
      handleDetail(row) {//跳转详情
        // return
        this.$router.push({ path: '/user/PaidMemberSettings/addedPaidUser', query: { id: row.id, type: 2,status:row.status } })

      },
      handstatus(row) {
        var data = {
          id: row.id
        }
        this.open(row)

      },
      open(row) {
        var mag = row.status == 0 ? '上架' : row.status == 1 ? '下架' : row.status == 2 ? '上架' : row.status
        this.$confirm('确定' + mag + '吗?, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(row.id).then(res => {
            this.$message({
              type: 'success',
              message: mag + '成功!'
            })
            this.getList()
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消成功'
          })
        })
      },
      getIndex(index) {
        return (index + 1) + (this.listQuery.page - 1) * this.listQuery.limit
      },
      // handleMoneyAndPoint(row) {
      //   var mp = ''

      //   if (row.money != undefined || row.money != null) {
      //     mp += '$' + row.money + this.$t('或者')
      //   }

      //   if (row.point != undefined || row.point != null) {
      //     mp += this.$t('积分') + row.point
      //   }
      //   return mp
      // },

      /**
       * 处理货币数据，返回带有货币符号的金额字符串
       * @param {Object} row - 行数据对象
       * @returns {string} - 带有货币符号的金额字符串
       */
      handleMoney(row) {
        var mp = ''
        if (row.money != undefined || row.money != null) {
          mp += '$' + row.money
        }
        return mp
      },

      /**
       * 处理积分数据，返回带有积分标识的积分字符串
       * @param {Object} row - 行数据对象
       * @returns {string} - 带有积分标识的积分字符串
       */
      handlePoint(row) {
        var mp = ''
        if (row.point != undefined || row.point != null) {
          mp += row.point + this.$t('积分')
        }
        return mp
      },

      filterAreaLimit(row){
        if(row.areaLimit == 1){
          return this.$t('限区域')
        }else{
          return this.$t('不限区域')
        }
      },

      // 自定义方法来拆分日期时间字符串
      formatDateTime(value) {
        if(value != undefined){
          // 创建 Date 对象来解析日期时间字符串
          const date = new Date(value);
          // 获取年月日部分并格式化
          const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
          return formattedDate;
        }else{
          return undefined
        }

      },
      // 自定义方法来拆分日期时间字符串
      formatTime(value) {
        if(value != undefined){
          // 创建 Date 对象来解析日期时间字符串
          const date = new Date(value);
          // 获取时分秒部分并格式化
          const formattedTime = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
          return formattedTime;
        }else{
          return undefined
        }
      },
      // 计算某一列数据的总和
      columnSum() {
        let sum = 0;
        // 遍历表格数据的每一行
        this.list.forEach(row => {
          // 累加某一列的值到总和中
          sum += row.currentNumbers; // 累加当前会员正在使用的人数
        });
        this.currentNumbersTotal = sum
      }
    }
  }
</script>

<style scoped>

</style>
